<?php
/**
 * Created by PhpStorm.
 * User: zhubing
 * Date: 2018/11/13
 * Time: 10:23
 * 短信接口类
 */
namespace app\common\service;
use think\Cache;
use think\Db;

class Sms {

    private $accessId = 'LTAI4FnKG268wVHiLhyxEiGQ';
    private $accessSecret = '6WsTZZlJOKWi0WvOnrV6gI3wckiOFX';
    private $signName = '以洽科技';

    public function __construct(){

    }

    //是否存在手机号码
    public function existMobile($param){

        $data = Db::name('user')->where('mobile',$param['mobile'])->field('id,mobile')->find();
        return isset($data['id']) ? 1 : 2;
    }

    //发送验证码短信
    public function sendCode($param){

        $data = $this->createCode($param);
        if(!$data){
            return ['code'=>0, 'msg'=>'发送失败~','errcode'=>'createcode error'];
        }
        //$json = $this->aliyunCode($param,$data);//阿里云短信
        $json = $this->sms10692Code($param,$data);
        $json['sendFlag'] = $this->createLog($json, $data);
        Cache::set('verificationCode_' . $param['mobile'], $data['code'], 60);
        return $json;
    }

    //发送自定义短信
    public function sendFixed($param, $data){

        $json = $this->aliyunFixed($param,$data);
        $json['sendFlag'] = $this->createLog($json, array_merge($param, $data));
        return $json;
    }

    //发送验证码短信[sms10692]
    public function sms10692Code($param,$data){
        $domain = $_SERVER['HTTP_HOST'];
        $program_c = config('program');
        $config = $program_c[$domain];
        $appid = $config['AppID'];
        $secret = $config['AppSecret'];
        $Company = $config['Company'];

        $post_data = array();
        $post_data['userid'] = 12782;
        $post_data['account'] = 'userxiaoxiao';
        $post_data['password'] = 'aa123456';
        $post_data['content'] = "【{$Company}】您的验证码为：{$data['code']}"; //短信内容
        $post_data['mobile'] = $param['mobile'];
        $post_data['sendtime'] = date('Y-m-d H:i:s'); //时定时发送，输入格式YYYY-MM-DD HH:mm:ss的日期值
        $url='http://sms10692.com/sms.aspx?action=send';
        $o='';
        foreach ($post_data as $k=>$v)
        {
            $o.="$k=".urlencode($v).'&';
        }
        $post_data=substr($o,0,-1);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //如果需要将结果直接返回到变量里，那加上这句。
        $result = curl_exec($ch);
        if($result){
            $flag = ['code'=>1,'errcode'=>'OK'];
        }else{
            $flag = ['code'=>0, 'msg'=>'发送失败~','errcode'=>'default error'];
        }
        return $flag;
    }

    //发送验证码短信[阿里云]
    public function aliyunCode($param, $data){

        AlibabaCloud::accessKeyClient($this->accessId, $this->accessSecret)->regionId('cn-hangzhou')->asDefaultClient();
        try {
            $flag = ['code'=>0, 'msg'=>'发送失败~','errcode'=>'default error'];
            $objs = AlibabaCloud::rpc()->product('Dysmsapi')->version('2017-05-25')
                ->action('SendSms')->method('POST')->options([
                    'query' => [
                        'RegionId' => "cn-hangzhou",
                        'PhoneNumbers' => $param['mobile'],
                        'TemplateCode' => "SMS_178550340",
                        'SignName' => $this->signName,
                        'TemplateParam' => json_encode($data),
                    ],
                ])->request();
            $json = $objs->toArray();
            if(isset($json['Code'])){
                if($json['Code'] == 'OK'){
                    $flag = ['code'=>1,'errcode'=>'OK'];
                }else{
                    if($json['Code'] == 'isv.BUSINESS_LIMIT_CONTROL'){
                        $flag = ['code'=>0,'msg'=>' 短信发送频率超限。','errcode'=>$json['Code']];
                    }
                }
            }
        } catch (ClientException $e) {
            $flag = ['code'=>0, 'msg'=>'发送失败~','errcode'=>'ClientException'];
        } catch (ServerException $e) {
            $flag = ['code'=>0, 'msg'=>'发送失败~','errcode'=>'ServerException'];
        }
        return $flag;
    }

    //发送自定义短信[阿里云]
    public function aliyunFixed($param,$data){

        AlibabaCloud::accessKeyClient($this->accessId, $this->accessSecret)->regionId('cn-hangzhou')->asDefaultClient();
        try {
            $flag = ['code'=>0, 'msg'=>'发送失败~','errmsg'=>'default error'];
            $objs = AlibabaCloud::rpc()->product('Dysmsapi')->version('2017-05-25')
                ->action('SendSms')->method('POST')->options([
                    'query' => [
                        'RegionId' => "cn-hangzhou",
                        'PhoneNumbers' => $param['mobile'],
                        'TemplateCode' => $param['tempid'],
                        'SignName' => $param['title'],
                        'TemplateParam' => json_encode($data),
                    ],
                ])->request();
            $json = $objs->toArray();
            if(isset($json['Code'])){
                if($json['Code'] == 'OK'){
                    $flag = ['code'=>1,'errcode'=>'OK'];
                }else{
                    if($json['Code'] == 'isv.BUSINESS_LIMIT_CONTROL'){
                        $flag = ['code'=>0,'msg'=>' 短信发送频率超限~','errcode'=>$json['Code']];
                    }
                }
            }
        } catch (ClientException $e) {
            $flag = ['code'=>0, 'msg'=>'发送失败~','errcode'=>'ClientException'];
        } catch (ServerException $e) {
            $flag = ['code'=>0, 'msg'=>'发送失败~','errcode'=>'ServerException'];
        }
        return $flag;
    }

    //生成短信发送认知
    public function createLog($json, $data){

        $data['content'] = json_encode($data);
        $data['status'] = $json['code'] == 1 ? 1 : 2;
        $data['errcode'] = $json['errcode'];
        $data['addtime'] = time();
        $data['adddate'] = date('Ymd',time());
        return Db::name('mess_sms')->strict(false)->insertGetId($data);
    }

    //生成短信验证码
    public function createCode($param){

        $code = rand(100000,999999);//生成6位验证码

        return ['code'=>$code];
    }

    //验证短信验证码
    public function checkCode($mobile, $smscode){

        $user_data = Db::name('user')->where(['mobile' => $mobile])->find();
        if($user_data['union_code'] != ''){
            $pass = substr($mobile,-6);
            if($pass == $smscode){
                return ['code'=>1];
            }
        }
        $mobiles = [
            15616169870,19118835207,13387419601,19974904831,18142609293,18075154271,13037313610,17773170609,15573179664,18684939948
        ];
        $wnycode = '123121';
        /*if(in_array($mobile, $mobiles) && $smscode == $wnycode){
            return ['code'=>1];
        }*/
        if($smscode == $wnycode){
            return ['code'=>1];
        }
        $map = [['mobile', '=', $mobile]];
        $log = Db::name('mess_sms_code')->field('id,pcode,addtime')->where($map)->order('id desc')->find();
        if(!isset($log['id'])){
            return ['code'=>0, 'msg'=>'请先获取短信验证码'];
        }
        if((NOW_TIME-$log['addtime']) >5*60){
            return ['code'=>0, 'msg'=>'您输入的验证码不正确'];
        }
        $code = myencrypt(strtoupper($smscode));
        if($code != $log['pcode']){
            return ['code'=>0, 'msg'=>'您输入的验证码不正确!'];
        }
        return ['code'=>1];
    }

    //图像检测
    public function faceDetect () {

        AlibabaCloud::accessKeyClient($this->accessId, $this->accessSecret)->regionId('cn-shanghai')->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                ->product('face')
                ->scheme('https')
                ->version('2018-12-03')
                ->action('DetectFace')
                ->method('POST')
                ->host('face.cn-shanghai.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "cn-shanghai",
                        'ImageUrl' => "http://cximg.yijia2016.com/img/head/2.png",
                    ],
                ])
                ->request();
            print_r($result->toArray());
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }
    }

}
